package com.itxzh.logindemo.utils;

import com.alibaba.fastjson.JSONObject;
import com.itxzh.logindemo.entities.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 简单Token工具
 *
 * @Author ldt
 * @Date 2022/5/20 15:23
 * @Version 1.0.0
 */
@Component
public class TokenRedisUtil {

    private static StringRedisTemplate stringRedisTemplate;

    private static final int TOKEN_TIME = 30;

    @Autowired
    private StringRedisTemplate _stringRedisTemplate;

    @PostConstruct
    public void init() {
        stringRedisTemplate = _stringRedisTemplate;
    }

    /**
     * 生成token，存储token-user关系
     * @param loginUser
     * @return token令牌
     */
    public static String generateToken(Users loginUser) {

        String token = UUID.randomUUID().toString().replaceAll("-", "");

        stringRedisTemplate.opsForValue().set(token, JSONObject.toJSONString(loginUser), TOKEN_TIME, TimeUnit.SECONDS);

        return token;
    }

    /**
     * 验证token是否有效
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        return stringRedisTemplate.hasKey(token);
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    public static Users getUser(String token) {
        String userJson = stringRedisTemplate.opsForValue().get(token);
        if(userJson != null) {
            return JSONObject.parseObject(userJson, Users.class);
        }
        return null;
    }

    /**
     * 刷新token过期时间
     * @param token
     * @return
     */
    public static void refresh(String token) {
        stringRedisTemplate.expire(token, TOKEN_TIME, TimeUnit.SECONDS);
    }
}
